package com.jyniubi.core.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jyniubi.base.exception.Assert;
import com.jyniubi.base.result.ResponseEnum;
import com.jyniubi.core.controller.api.ApiIntegralGradeController;
import com.jyniubi.core.enums.BorrowInfoStatusEnum;
import com.jyniubi.core.enums.BorrowerStatusEnum;
import com.jyniubi.core.pojo.entity.*;
import com.jyniubi.core.mapper.BorrowInfoMapper;
import com.jyniubi.core.pojo.vo.BorrowInfoApprovalVO;
import com.jyniubi.core.pojo.vo.BorrowInfoVO;
import com.jyniubi.core.pojo.vo.BorrowerDetailVO;
import com.jyniubi.core.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author jyzhang
 * @since 2024-04-27
 */
@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {
    @Resource
    private IntegralGradeService integralGradeService;
    @Resource
    private DictService dictService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private BorrowerService borrowerService;
    @Resource
    private LendService lendService;
    @Override
    public void saveBorrowInfo(BorrowInfo borrowInfo, Long userId) {
        borrowInfo.setUserId(userId);
        //验证用户借款金额不能超过自己允许的额度
        BigDecimal borrowAmount = integralGradeService.borrowAmount(userId);
        Assert.assertTrue(borrowInfo.getAmount().compareTo(borrowAmount)>0, ResponseEnum.USER_AMOUNT_ERROR);
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());
        BigDecimal decimal = borrowInfo.getBorrowYearRate().divide(new BigDecimal(100), 8,
                BigDecimal.ROUND_DOWN);
        borrowInfo.setBorrowYearRate(decimal);
        this.save(borrowInfo);
    }

    @Override
    public Integer getBorrowStatus(Long userId) {
        BorrowInfo borrowInfo = this.getOne(Wrappers.lambdaQuery(BorrowInfo.class)
                .eq(BorrowInfo::getUserId, userId)
                .orderByDesc(BorrowInfo::getCreateTime)
                .last("limit 1"));
        if (borrowInfo == null || borrowInfo.getStatus() == 3){
            return 0;
        }
        return borrowInfo.getStatus();
    }

    @Override
    public List<BorrowInfoVO> getBorrowInfoVOs() {
        List<BorrowInfo> borrowInfoList = this.list();
        List<BorrowInfoVO> borrowInfoVOS = borrowInfoList.stream().map(borrowInfo -> {
            return getBorrowInfoVO(borrowInfo);
        }).collect(Collectors.toList());
        return borrowInfoVOS;
    }

    @Override
    public Map<String, Object> getBorrowInfoDetails(String id) {
        BorrowInfo borrowInfo = this.getById(id);
        BorrowInfoVO borrowInfoVO = getBorrowInfoVO(borrowInfo);
        Long userId = borrowInfo.getUserId();
        Borrower borrower = borrowerService.getOne(Wrappers.lambdaQuery(Borrower.class)
                .eq(Borrower::getUserId, userId)
                //只需要一个id即可.
                .select(Borrower::getId));
        BorrowerDetailVO borrowerDetail = borrowerService.getBorrowerDetailById(borrower.getId().toString());
        Map<String,Object> map = new HashMap<>();
        map.put("borrowInfoVO",borrowInfoVO);
        map.put("borrowerDetailVO",borrowerDetail);
        return map;
    }

    @Override
    public void approval(BorrowInfoApprovalVO borrowInfoApprovalVO) {
        //通过前端的id来获取对应的borrowInfo对象
        Long id = borrowInfoApprovalVO.getId();
        BorrowInfo borrowInfo = this.getById(id);
        //更改borrowInfo对象的状态
        borrowInfo.setStatus(borrowInfoApprovalVO.getStatus());
        //设置更新时间为空，更新时会自动注入更新时间
        borrowInfo.setUpdateTime(null);
        //执行更新数据
        this.updateById(borrowInfo);
        //如果审批状态不为审批通过，则结束任务，不必再插入lend表格
        if (!borrowInfoApprovalVO.getStatus().equals(BorrowerStatusEnum.AUTH_OK.getStatus())){
            return;
        }
        //审批通过，生产新的标的
        lendService.createLend(borrowInfo,borrowInfoApprovalVO);
    }

    private BorrowInfoVO getBorrowInfoVO(BorrowInfo borrowInfo) {
        BorrowInfoVO borrowInfoVO = new BorrowInfoVO();
        BeanUtils.copyProperties(borrowInfo,borrowInfoVO);
        borrowInfoVO.setBorrowYearRate(borrowInfo.getBorrowYearRate()
                .multiply(new BigDecimal(100)).toString()+"%");
        Dict dict = dictService.getDictByDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
        borrowInfoVO.setReturnMethod(dict.getName());
        dict = dictService.getDictByDictCodeAndValue("moneyUse", borrowInfo.getReturnMethod());
        borrowInfoVO.setMoneyUse(dict.getName());
        switch (borrowInfo.getStatus()){
            case 0 :
                borrowInfoVO.setStatus(BorrowInfoStatusEnum.NO_AUTH.getMsg());
                break;
            case 1:
                borrowInfoVO.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getMsg());
                break;
            case 2:
                borrowInfoVO.setStatus(BorrowInfoStatusEnum.CHECK_OK.getMsg());
                break;
            default:
                borrowInfoVO.setStatus(BorrowInfoStatusEnum.CHECK_FAIL.getMsg());
                break;
        }
        UserInfo userInfo = userInfoService.getById(borrowInfo.getUserId());
        borrowInfoVO.setMobile(userInfo.getMobile());
        borrowInfoVO.setName(userInfo.getName());
        return borrowInfoVO;
    }
}
